package zzf;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {

    /*
    * 多文件的上传
    * */
    @RequestMapping("/upload")
    public String upload(@RequestParam(value = "username",required = false)String username,
                         @RequestParam(value = "headerimg",required = true)MultipartFile[] files,
                         Model model){

        for (MultipartFile file : files) {
            if (!file.isEmpty()){
                System.out.println("上传文件的名字"+file.getName());
                System.out.println("上传文件的名字"+file.getOriginalFilename());

                //文件保存
                File file1 = new File("/Users/zuozhongfei/Desktop/学习/Java/SpringMVC/SpringMVC/07-SpringMVC_UploadFile/file/" + file.getOriginalFilename());
                try {
                    file.transferTo(file1);
                    model.addAttribute("msg","文件上传成功");
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("msg","文件上传失败"+e.getMessage());
                }
            }
        }

        return "forward:/index.jsp";
    }

    /*
    * 单文件的上传
    * */
    @RequestMapping("/uploadSingle")
    public String uploadSingle(@RequestParam(value = "username", required = false) String username,
                          @RequestParam(value = "headerimg", required = true) MultipartFile file,
                          Model model) {

        System.out.println("上传文件的名字" + file.getName());
        System.out.println("上传文件的名字" + file.getOriginalFilename());

        //文件保存
        File file1 = new File("/Users/zuozhongfei/Desktop/学习/Java/SpringMVC/SpringMVC/07-SpringMVC_UploadFile/file/" + file.getOriginalFilename());
        try {
            file.transferTo(file1);
            model.addAttribute("msg", "文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("msg", "文件上传失败" + e.getMessage());
        }

        return "forward:/index.jsp";
    }
}
